package com.example.prison.util;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TCPClient {
   private final Logger logger = LoggerFactory.getLogger(TCPClient.class);
   private static final EventLoopGroup group = new NioEventLoopGroup();

   public void run(String ip, int port) throws Exception {
      try {
         Bootstrap bootstrap = new Bootstrap();
         ((Bootstrap)((Bootstrap)((Bootstrap)bootstrap.group(group)).channel(NioSocketChannel.class)).option(ChannelOption.SO_KEEPALIVE, true)).handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel socketChannel) throws Exception {
               ChannelPipeline pipeline = socketChannel.pipeline();
               pipeline.addLast(new ChannelHandler[]{new StringEncoder(CharsetUtil.UTF_8)});
               pipeline.addLast(new ChannelHandler[]{new StringDecoder(CharsetUtil.UTF_8)});
               pipeline.addLast(new ChannelHandler[]{new TCPClientHandler()});
            }
         });
         ChannelFuture channelFuture = bootstrap.connect(ip, port).sync();
         channelFuture.channel().closeFuture().sync();
      } finally {
         group.shutdownGracefully();
      }

   }
}
